package com.xja.config;

import com.xja.interceptor.AdminLoginInterceptor;
import com.xja.interceptor.AdminRefreshTokenInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author 蔡建国
 * Date  2025/6/10 16:03
 */
@Configuration
@RequiredArgsConstructor
public class MvcConfig implements WebMvcConfigurer {

    private final StringRedisTemplate redisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 管理端
        // 第一个拦截器：刷新token有效期的拦截器
        registry.addInterceptor(new AdminRefreshTokenInterceptor(redisTemplate))
                .addPathPatterns("/admin/**")
                .order(0);

        // 添加校验登录的拦截器，且排除一些不用鉴权的接口
        registry.addInterceptor(new AdminLoginInterceptor())
                .addPathPatterns("/admin/**")
                .excludePathPatterns(
                        "/admin/employee/login",
                        "/admin/employee/loginByPhone",
                        "/admin/employee/sendSmsCode",
                        "/admin/employee/register/**",
                        "/admin/employee/logout"
                ).order(1);
    }

    // 跨域问题处理
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}
